package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.mapper.UserMapper;
import com.bwie.state.CheckEnum;
import com.bwie.utils.R;
import com.bwie.vo.AdminLoginVo;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 陶仕豪
 * @description 针对表【tb_user(用户表)】的数据库操作Service实现
 * @createDate 2025-04-21 16:08:10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    HttpServletRequest request;

    @Override
    public R getUserById(Integer id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return R.ERROR(404, "用户不存在");
        }
        //设置密码为空 防止密码泄露
        user.setUserPass(null);
        return R.OK(user);
    }

    @Override
    public R adminLogin(AdminLoginVo adminLoginVo) {
        //获取用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName, adminLoginVo.getUserName()));

        if (user == null) {
            return R.ERROR(404, "用户不存在");
        }

        //校验密码
        if (!user.getUserPass().equals(adminLoginVo.getUserPass())) {
            return R.ERROR(500, "密码错误");
        }

        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", user.getUserId())
                .claim("userName", user.getUserName())
                .claim("nickName", user.getNickName()).compact();

        //缓存token
        String redisKey = "token-" + user.getUserId();
        redisTemplate.opsForValue().set(redisKey, token, 60, TimeUnit.MINUTES);
        //返回token
        user.setToken(token);
        user.setUserPass(null);
        return R.OK(user);
    }

    @Override
    public R getUserList(PageInfoVo pageInfoVo) {
        Page<User> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(pageInfoVo.getKeyWord())) {
            wrapper.lambda().like(User::getNickName, pageInfoVo.getKeyWord())
                    .or().like(User::getUserEmail, pageInfoVo.getKeyWord())
                    .or().like(User::getUserName, pageInfoVo.getKeyWord())
                    .or().like(User::getUserMobile, pageInfoVo.getKeyWord());

        }
        wrapper.lambda().orderByDesc(User::getUserId);
        Page<User> user = userMapper.selectPage(page, wrapper);
        return R.OK(user);
    }

    @Override
    public R userReg(User user) {
        //校验用户名是否存在  唯一校验
        User one = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUserName, user.getUserName()));
        if (one != null) {
            return R.ERROR(500, "用户名重复");
        }
        //添加用户
        user.setCreateTime(new Date());
        userMapper.insert(user);
        return R.OK();
    }

    @Override
    public R checkUser(User user) {
        //判断用户是否存在
        User user1 = userMapper.selectById(user.getUserId());
        if (user1 == null) {
            return R.ERROR(500, "用户不存在");
        }

        //如果审核驳回  填写原因
        if (user.getUserStatus().equals(CheckEnum.CHECK_NO.getCode())) {

            //审核驳回
            if (StringUtils.isEmpty(user.getReason())) {
                return R.ERROR(500, "审核驳回必须填写驳回原因");
            }
        }
        //审核
        user.setUserStatus(user.getUserStatus());
        user.setReason(user.getReason());
        userMapper.updateById(user);

        return R.OK();
    }

    @Override
    public R getMyInfo() {
        //获取token
        String token = request.getHeader("token");
        if(token==null){
            return R.ERROR(500,"请先登录");
        }
        //解析token
        Integer userId = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("userId", Integer.class);

        //获取用户信息并返回
        User user = userMapper.selectById(userId);
        return R.OK(user);
    }

    @Override
    public R updateUser(User user) {
        User user1 = userMapper.selectById(user.getUserId());
        if(user1==null){
            return R.ERROR(404,"用户不存在");
        }
        userMapper.updateById(user);
        return R.OK();
    }
}




